var ws = require('ws');

; (function (ws) {

  var options = {
    port: 8000
  }

  var server = new ws.Server(options);

  const init = () => {
    bindEvent();
  }

  function bindEvent() {
    server.on('open', handleOpen);
    server.on('close', handleClose);
    server.on('error', handleError);
    server.on('connection', handleConnection);
  }

  function handleOpen(event) {
    console.log('BE：WebSocket open');
    console.log(event);
  }

  function handleClose(event) {
    console.log('BE：WebSocket close');
    console.log(event);
  }

  function handleError(event) {
    console.log('BE：WebSocket error');
    console.log(event);
  }

  function handleConnection(ws) {
    console.log('BE：WebSocket connection');
    // console.log(event);
    ws.on('message', handleMessage);
  }

  function handleMessage(message) {
    console.log(message);
    // 广播消息给每一个连接到此服务的客户端
    server.clients.forEach(function (client) {
      client.send(message);
    })
  }

  init();
})(ws);